#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
在线密码管理平台 - 模块化主程序入口
子鞍科技股份有限公司
"""
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.middleware.sessions import SessionMiddleware

# 导入模块
import datetime
import os
from modules.utils.config import load_config, config
from modules.database import init_database

# 设置时区
timezone = None

from modules.auth import auth_router
from modules.password import password_router
from modules.share import share_router
from modules.admin import admin_router
from modules.user import user_router
from modules.export import export_router
from modules.calendar import calendar_router

# 初始化FastAPI应用
app = FastAPI(title="在线密码管理平台", description="子鞍科技密码管理系统")

# 添加会话中间件
app.add_middleware(SessionMiddleware, secret_key="guzian.cn")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 模板配置
templates = Jinja2Templates(directory="templates")

# 注册路由
app.include_router(auth_router)
app.include_router(password_router)
app.include_router(share_router)
app.include_router(admin_router)
app.include_router(user_router)
app.include_router(export_router)
app.include_router(calendar_router)


# 全局异常处理器
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code == 401:
        from fastapi.responses import RedirectResponse
        return RedirectResponse(url="/login", status_code=302)
    elif exc.status_code == 403:
        return templates.TemplateResponse("error.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "error_code": 403,
            "error_message": "权限不足"
        }, status_code=403)
    elif exc.status_code == 404:
        return templates.TemplateResponse("error.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "error_code": 404,
            "error_message": "页面不存在"
        }, status_code=404)
    else:
        return templates.TemplateResponse("error.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "error_code": exc.status_code,
            "error_message": exc.detail
        }, status_code=exc.status_code)


@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    load_config()
    # 设置时区
    global timezone
    timezone_str = config.get('DEFAULT', 'timezone', fallback='Asia/Shanghai')
    try:
        # 使用zoneinfo (Python 3.9+)
        from zoneinfo import ZoneInfo
        timezone = ZoneInfo(timezone_str)
    except ImportError:
        # 回退到pytz (如果安装了)
        try:
            import pytz
            timezone = pytz.timezone(timezone_str)
        except ImportError:
            # 如果都没有，使用系统默认时区
            timezone = datetime.timezone.utc
            print(f"警告: 无法设置时区 {timezone_str}，使用系统默认时区")
    init_database()


if __name__ == "__main__":
    import uvicorn
    load_config()
    port = int(config.get('DEFAULT', 'web_port', fallback=8090))
    uvicorn.run(app, host="0.0.0.0", port=port)